import { Rating, Stack, Typography, styled } from '@mui/material'
import { useParams } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { useGetProductQuery } from '../../api/productsApiSlice'
import { GoBackButton } from '../shared/goBackButton'

const StyledContainer = styled('div')(() => ({
	display: 'flex',
	marginBottom: '10px',
	width: '100%',
	flexDirection: 'column',
}))

const StyledName = styled(Typography)(() => ({
	styleName: 'Header : H1/ExtraBold',
	fontFamily: 'Nunito',
	fontSize: '28px',
	fontWeight: '800',
	lineHeight: '32px',
	letterSpacing: '0em',
	textAlign: 'left',
}))

const Heading = () => {
	const { productId } = useParams()
	const { data: productData } = useGetProductQuery({ id: productId || '' })
	const [rating, setRating] = useState(0)
	const [reviews, setReviews] = useState(0)

	useEffect(() => {
		const ratingArray = productData?.reviews.map(({ rating }) => rating)
		if (ratingArray) {
			setRating(ratingArray.reduce((a, b) => a + b, 0) / ratingArray.length)
			setReviews(ratingArray.length)
		}
	}, [productData?.reviews])

	return (
		<StyledContainer>
			<GoBackButton />
			<StyledName>{productData?.name}</StyledName>
			<Stack direction={'row'} spacing={2}>
				<Rating
					name='half-rating-read'
					value={rating}
					precision={0.5}
					readOnly
				/>
				<Typography>
					{reviews !== 0 ? `${reviews} отзыв` : 'Нет отзывов'}
				</Typography>
			</Stack>
		</StyledContainer>
	)
}

export default Heading
